#! /bin/bash
# author: 我的代码温柔如风
# see the link below:
# https://artifacthub.io/packages/helm/prometheus-community/prometheus
# https://artifacthub.io/packages/helm/grafana/grafana

my_name=monitor
my_namespace=kubernetes-${my_name}

echo "=================================================="
echo "1、添加镜像地址"
echo "=================================================="
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo add kube-state-metrics https://kubernetes.github.io/kube-state-metrics
helm repo add grafana https://grafana.github.io/helm-charts
helm repo update

echo "=================================================="
echo "2、安装Prometheus+Grafana"
echo "=================================================="

echo "create namespace ..."
# 检查命名空间是否存在 如不存在则创建
kubectl get namespaces | grep ${my_namespace}
if [ $? -eq 0 ]; then
  echo "命名空间 ${my_namespace} 已存在～"
else
  echo "未检测到 ${my_namespace}!!!"
  kubectl create namespace ${my_namespace}
  echo "创建 ${my_namespace} 完成"
fi

echo "install grafana ..."
kubectl get pods --namespace ${my_namespace} | grep "${my_name}-grafana"
if [ $? -eq 0 ]; then
  echo "应用 ${my_name}-grafana 已存在～"
else
  echo "未检测到 ${my_name}-grafana!!!"

  helm install ${my_name}-grafana grafana/grafana --namespace=${my_namespace}

  kubectl get secret --namespace ${my_namespace} ${my_name}-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo

  export POD_GRAFANA=$(kubectl get pods --namespace ${my_namespace} -l "app.kubernetes.io/name=grafana,app.kubernetes.io/instance=${my_name}-grafana" -o jsonpath="{.items[0].metadata.name}")
  kubectl --namespace ${my_namespace} port-forward $POD_GRAFANA 3000

  echo "创建 ${my_name}-grafana 完成"
fi

echo "install prometheus ..."
kubectl get pods --namespace ${my_namespace} | grep "${my_name}-prometheus"
if [ $? -eq 0 ]; then
  echo "应用 ${my_name}-prometheus 已存在～"
else
  echo "未检测到 ${my_name}-prometheus!!!"

  helm install ${my_name}-prometheus prometheus-community/prometheus --namespace=${my_namespace}

  export POD_PROM_SVR=$(kubectl get pods --namespace ${my_namespace} -l "app=prometheus,component=server" -o jsonpath="{.items[0].metadata.name}")
  kubectl --namespace ${my_namespace} port-forward $POD_PROM_SVR 9090

  export POD_PROM_PG=$(kubectl get pods --namespace ${my_namespace} -l "app=prometheus,component=pushgateway" -o jsonpath="{.items[0].metadata.name}")
  kubectl --namespace ${my_namespace} port-forward $POD_PROM_PG 9091

  export POD_PROM_AM=$(kubectl get pods --namespace ${my_namespace} -l "app=prometheus,component=alertmanager" -o jsonpath="{.items[0].metadata.name}")
  kubectl --namespace ${my_namespace} port-forward $POD_PROM_AM 9093

  echo "创建 ${my_name}-prometheus 完成"
fi

echo "=================================================="
echo "3、完成"
echo "=================================================="
